<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\Photo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PhotoController extends Controller
{
    public function index(Request $request)
    {
        $aid = $request->input('aid');//相册id
        $uid = Auth::id();
        $photos = Photo::where(['uid'=>$uid,'aid'=>$aid])->get();
        $data = [];
        foreach ($photos as $photo){
            $data[] = [
                'id' => $photo->id,
                'url' => $photo->url
            ];
        }
        return $this->renderJson($data);
    }

    public function store(Request $request)
    {

        $this->validate($request,[
           'aid' => 'required',
           'url' => 'required|string'
        ],[
            'required' => ':attribute不能为空'
        ],[
            'aid' => '相册id',
            'url' => '图片地址'
        ]);

        $data = [
            'uid' => Auth::id(),
            'aid' => $request->input('aid'),//相册id
            'url' => $request->input('url')
        ];

        if (Photo::create($data)){
            return $this->success('添加成功');
        }
        return $this->error('添加失败');
    }

    public function destroy($id)
    {
        $photo = Photo::findOrFail($id);

        try {
            if ($photo->delete()) {
                return $this->renderJson();
            }
        } catch (\Exception $e) {

        }
        return $this->error('删除失败');
    }
}
